<template>
    <Layout>
        <Form :label-width="120" ref="formInline" :model="formInline">
            <Row class="query-form">
                <Col span="8">
                    <FormItem label="所属单位：">
                        <cascaderDom ref="queryOrgCascader" @setOrgInfo="setOrgId1" @setOrgname="setOrgName1"
                                     :rootOrgId="companyId"
                                     :orgTree="true"></cascaderDom>
                    </FormItem>
                </Col>
                <Col span="8" >
                    <FormItem label="分组名称：" prop="teamName">
                        <Input v-model="formInline.teamName" />
                    </FormItem>
                </Col>
                <Col span="8">
                    <Button @click="cancel" class="ivu-btn-reset">重置</Button>
                    <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                </Col>
            </Row>
        </Form>
        <Row class="query-form">
            <Col span="24">
                <Button size="large" class="ivu-btn-add" icon="md-add" @click="addModel">新增</Button>
            </Col>
        </Row>
        <Table ref='table' :loading="loading" border :columns="baseColumns"
               :data="baseData" no-data-text="没有查询到相关数据!"  :height="tableHeight" highlight-row stripe size="small">
            <template slot-scope="{ row, index }" slot="userInfo">
                <Button type="error" size="small" @click="bindUsers(row)">绑定用户</Button>
            </template>
        </Table>
        <Row style="margin-right:10px;">
            <Col span="24">
                <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
                      @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
            </Col>
        </Row>
        <Modal v-model="modal1" title="组别维护" width="700" :mask-closable="false">
            <Form :label-width="100" ref="formCustom" :model="form1data" :rules="ruleCustom">
                <Row>
                    <i-col>
                        <FormItem label="所属公司：" prop="companyId">
                            <cascaderDom ref="childOrg"
                                         @setOrgInfo='setOrgId'
                                         @setOrgname='setOrgName'
                                         :setCurrentName="{label:form1data.orgName,value:form1data.orgId}"
                                         :orgTree="true" :rootOrgId="companyId"></cascaderDom>
                        </FormItem>
                    </i-col>
                </Row>
                <Row>
                    <i-col>
                        <FormItem label="分组名称：" prop="teamName">
                            <Input v-model="form1data.teamName" show-word-limit :maxlength="200" placeholder="请输入..."/>
                        </FormItem>
                    </i-col>
                </Row>
                <Row>
                    <i-col>
                        <FormItem label="分组描述：" prop="teamNote">
                            <Input v-model="form1data.teamNote" show-word-limit :maxlength="200" placeholder="请输入..."/>
                        </FormItem>
                    </i-col>
                </Row>
            </Form>
            <div slot="footer">
                <Button  class='ivu-btn-save' :loading="buttonLoading" @click="saveInfo">确定</Button>
                <Button class='ivu-btn-cancel' @click="closeModal">取消</Button>
            </div>
        </Modal>

        <Modal v-model="visibleBindedUsers" title="已绑定用户" width="850" footer-hide :mask-closable="false" @on-cancel="visibleBindedUsers=false,paperTeamId=''">
            <paper-team-user v-if="visibleBindedUsers" :paperTeamId="paperTeamId" :orgName="orgName" :buttonDisabled="buttonDisabled"
                             :visibleBindedUsers="visibleBindedUsers"></paper-team-user>
        </Modal>
    </Layout>
</template>

<script>
    import {Api} from '@/api'
    import qs from "qs";
    import {sessionStorage, cookie} from '@/common/cacheUtils.js';
    import cascaderDom from "../../../../components/cascader-dom.vue"
    import {formatDate} from '@/tools/index'
    import paperTeamUser from "./paperTeamUser";

    export default {
        name: "questionBase",
        components: {cascaderDom,paperTeamUser},
        data(){
            return{
                loading: true,
                formInline:{
                    teamName: ''
                },
                tableHeight: '',
                pageSizeArray: [10, 20, 50],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1
                },
                modal1: false,
                form1data: {},
                ruleCustom: {
                    teamName: [{required: true, message: ' ',trigger: 'blur' }],
                    // teamNote: [{required: true,message: ' ',trigger: 'blur' }],
                    orgId:[{ required: true, message: ' ',trigger: 'blur'}],
                },
                baseColumns: [
                    {type: 'index', title: '编号', width: 80, align: 'center', fixed: 'left'},
                    {title: '所属公司', minWidth:200,align: 'center', key: 'orgName'},
                    {title: '分组名称', minWidth:180,align: 'center', key: 'teamName'},
                    {title: '分组描述',minWidth:180, align: 'center', key: 'teamNote',tooltip:true},
                    {title: '分组人员数量',minWidth:100, align: 'center', key: 'teamUserNum'},
                    {title: '分组创建时间',minWidth:100, align: 'center', key: 'createTime',render:(h, params)=> {
                            if (!params.row['createTime']) return "";
                            return h('span', formatDate(new Date(params.row['createTime']), "yyyy-MM-dd"))}},
                    {title: '分配用户',minWidth:90, align: 'center', slot: 'userInfo'},
                    {
                        title: '操作',
                        align: 'center',
                        key: 'view',
                        fixed: 'right',
                        width: 120,
                        render: (h, params) => {
                            let flag = this.currentUser.loginId === this.Common.admin || this.currentUser.userId === params.row.createUserId  || this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined
                                ||sessionStorage('userId').getObject('userId').userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: flag ? '':'#d0d0d0' ,
                                        pointerEvents: flag ? '' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.form1data = {...params.row};
                                            this.modal1 = true;
                                        }
                                    }
                                }, '修改'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: flag ? 'red':'#d0d0d0' ,
                                        pointerEvents: flag ? '' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.deleteRow(params.row);
                                        }
                                    }
                                }, '删除'),
                            ]);
                        }
                    }
                ],
                buttonLoading:false,
                baseData: [],
                companyId:'',
                currentUser: JSON.parse(sessionStorage('userId').get('userId')),

                visibleBindedUsers:false,
                paperTeamId:'',
                orgName:'',
                buttonDisabled: false
            }
        },
        mounted(){
            this.companyId=sessionStorage('userId').getObject('userId').companyId
            this.tableHeight = window.innerHeight*0.85 - this.$refs.table.$el.offsetTop-40;
            this.query();
        },
        watch: {
            "modal1": function (qw, er) {
                if (qw && this.modal1) {
                    setTimeout(() => {
                        this.$refs.childOrg.setCurrentOrg();
                    }, 100)
                } else {
                    this.$refs.childOrg.resetCurrentOrg();
                    this.query()
                }
            },
        },
        methods:{
            bindUsers(data) {
                this.buttonDisabled = this.currentUser.loginId === this.Common.admin || this.currentUser.userId === data.createUserId  || this.currentUser.userRole.find(obj => obj.roleId == '73b38b37dff64392ba0ee7dd579bf293') != undefined || this.currentUser.userBeHandedOver.find(obj => obj == params.row.createUserId) != undefined
                this.visibleBindedUsers = true
                this.paperTeamId = data.id
                this.orgName = data.orgName
            },

            query(){
                this.loading = true;
                let data = {
                    pageNumber: this.pagedata.currentPage,
                    pageSize: this.pagedata.pageSize,
                };
                if (this.formInline.companyId != null&&this.formInline.companyId != undefined&&this.formInline.companyId != '') {
                    this.formInline.orgId=this.formInline.companyId
                }else {
                    this.formInline.orgId = sessionStorage('userId').getObject('userId').companyId
                }
                data = Object.assign(data,JSON.parse(JSON.stringify(this.formInline)));
                this.$http.get(Api.paperTeam,{
                    params:data,
                    paramsSerializer: params => {
                        return qs.stringify(params, { indices: false })
                    }
                }).then((res) => {
                    this.baseData = res.data.data.data;
                    this.pagedata.total = res.data.data.totalSize;
                    this.loading = false;
                }).catch( e => {
                    this.$Message.error('请求失败');
                });
            },

            pageSizeChange(pageSize){
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            pageChange(pageNum){
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            cancel(){
                this.pagedata.currentPage = 1
                this.formInline = {};
                this.query();
                this.$refs.queryOrgCascader.resetCurrentOrg();
            },
            addModel(){
                this.form1data = {};
                this.modal1 = true;
            },
            saveInfo(){
                this.$refs['formCustom'].validate((valid) => {
                    if(valid){
                        this.buttonLoading = true
                        this.$http.post(Api.paperTeam+'/saveOrUpdate', this.form1data).then((res) => {
                            this.query();
                            this.$Message.success({
                                content: '成功',
                                duration: 4
                            });

                            this.modal1 = false;
                            this.buttonLoading = false
                        }).catch( e => {
                            this.$Message.error({
                                content: '请求失败',
                                duration: 4
                            });
                            this.buttonLoading = false
                        });
                    }else {
                        this.$Message.error('请填报完整!');
                    }
                })
            },
            deleteRow(row){
                this.$Modal.confirm({
                    title: '数据删除',
                    content: '<p>确定删除该分组</p>',
                    okText: '确认',
                    onOk: () => {
                        this.$http.delete(Api.paperTeam+'/deletePaperTeamById/'+row.id).then((res) => {
                            this.$Message.success({content:'删除成功',duration: 4});
                            this.modal1 = false;
                            this.query();
                        })
                    },
                    cancelText: '取消'
                });
            },
            closeModal(){
                this.form1data = {};
                this.modal1 = false;
            },
            setOrgId(data) {
                if (data && data instanceof Array && data.length > 0) {
                    this.$set(this.form1data, 'orgId', data[data.length - 1])
                } else {
                    this.form1data.orgId = null;
                }
            },
            setOrgName(data) {
                this.form1data.orgName = data;
            },
            setOrgId1(data) {
                this.formInline.companyId = data[data.length - 1];
            },
            setOrgName1(data) {
                this.formInline.companyName = data;
            },

        }
    }
</script>

<style lang='css' scoped>
    @import '../../../../index.css';
</style>
